const Router = require('koa-router');
const router = new Router();

const keywordLogic = require('../business-logic/keyword');
const emailLogic = require('../business-logic/email')

router.get('/keywords', async(ctx, next) => {
    let query = ctx.request.query;
    let filter = {
        state: 1
    };
    let keywords = await keywordLogic.query(query.pageNum, query.pageCount, filter);
    let total = await keywordLogic.total();
    ctx.send({
        code: 200,
        data: {
            keywords: keywords,
            total: total
        }
    })
})

router.post('/keyword', async(ctx, next) => {
    let body = ctx.request.body;
    await keywordLogic.save(body);
    ctx.send({
        code: 200,
        msg: 'save keyword success'
    });
})

router.put('/keyword', async(ctx, next) => {
    let body = ctx.request.body;
    await keywordLogic.update(body);
    ctx.send({
        code: 200,
        msg: 'update keyword success'
    });
})

router.get('/keyword-emails/:id', async(ctx, next) => {
    let keywordId = ctx.params.id;
    let keyword = await keywordLogic.queryById(keywordId);
    if (!keyword) {
        ctx.send({
            code: 404,
            msg: 'Not Found'
        });
        return;
    }
    let emails = await emailLogic.queryByIds(keyword.emailIds);
    ctx.send({
        code: 200,
        data: emails
    });
})

router.delete('/keyword-email', async(ctx, next) => {
    let { keywordId, emailId } = ctx.query;
    await keywordLogic.removeEmail(keywordId, emailId);
    ctx.send({
        code: 200,
        msg: 'remove email success.'
    });
})

router.delete('/keyword/:id', async(ctx, next) => {
    let id = ctx.params.id;
    await keywordLogic.remove(id);
    ctx.send({
        code: 200,
        msg: 'keyword remove success.'
    });
})

module.exports = router;